<template>
	<el-form ref="formRef" class="login-content-form" size="large" :model="state.ruleForm" :rules="rules">
		<el-form-item class="login-animation1" prop="userName">
			<el-input
				v-model="state.ruleForm.userName"
				clearable
				placeholder="多种角色：admin、common、test、commonTest"
			>
				<template #prefix>
					<el-icon class="el-input__icon"><ele-User /></el-icon>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2" prop="password">
			<el-input
				:type="state.isShowPassword ? 'text' : 'password'"
				v-model="state.ruleForm.password"
				placeholder="密码：123456"
			>
				<template #prefix>
					<el-icon class="el-input__icon"><ele-Unlock /></el-icon>
				</template>
				<template #suffix>
					<i
						class="iconfont el-input__icon login-content-password"
						:class="state.isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
						@click="state.isShowPassword = !state.isShowPassword"
					>
					</i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation3" prop="code">
			<el-col :span="15">
				<el-input
					v-model="state.ruleForm.code"
					clearable
					maxlength="4"
					placeholder="验证码不区分大小写"
					@keyup.enter.native="onSignIn"
				>
					<template #prefix>
						<el-icon class="el-input__icon"><ele-Position /></el-icon>
					</template>
				</el-input>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="8">
				<HIdentifyCode ref="iCode" v-model="state.identifyCode" />
			</el-col>
		</el-form-item>
		<el-form-item class="login-animation4">
			<el-button
				type="primary"
				class="login-content-submit"
				round
				v-waves
				@click="onSignIn"
				:loading="state.loading"
			>
				<span>登 录</span>
			</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup lang="ts" name="loginAccount">
import { ref, reactive, defineAsyncComponent } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { Local } from "/@/utils/storage";
import { formatAxis } from "/@/utils/formatTime";
import { NextLoading } from "/@/utils/loading";
import { userLogin } from "/@/api/login";

// 引入组件
const HIdentifyCode = defineAsyncComponent(() => import("/@/components/identityCode/index.vue"));

// 定义变量内容
const route = useRoute();
const router = useRouter();
const formRef = ref();
const iCode = ref();
const state = reactive({
	identifyCode: "",
	isShowPassword: false,
	ruleForm: {
		userName: "admin",
		password: "123456",
		code: "",
	},
	loading: false,
});

// 定义表单校验规则
const rules = reactive<FormRules>({
	userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
	password: [{ required: true, message: "请输入密码", trigger: "blur" }],
	code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

// 登录
const onSignIn = () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			if (state.ruleForm.code.toLocaleLowerCase() != state.identifyCode.toLocaleLowerCase()) {
				iCode.value.refreshCode(); // 刷新验证码
				return ElMessage.error("验证码错误，请重新输入");
			}
			state.loading = true;
			const loginData = {
				name: state.ruleForm.userName,
				pwd: state.ruleForm.password,
			};
			try {
				const { code, data } = await userLogin(loginData);
				if (code !== 200) throw new Error();
				Local.set("token", data.token);
				Local.set("refresh", data.token);
				Local.set("userInfo", data.userInfo);
				signInSuccess(); // 登录成功后的跳转
			} catch (error) {
				state.loading = false;
				ElMessage.error("登录失败");
				iCode.value.refreshCode();
				Local.remove("token");
				Local.remove("refresh");
				Local.remove("userInfo");
				console.error(error);
			}
		}
	});
};

// 登录成功后的跳转
const signInSuccess = () => {
	// 登录成功后跳转至首页，或重定向到对应的路径中
	if (route.query?.redirect) {
		router.push({
			path: <string>route.query?.redirect,
			query:
				Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : "",
		});
	} else {
		router.push("/home");
	}
	// 登录成功提示
	ElMessage.success(`${formatAxis(new Date())}，欢迎回来！`);
	// 添加 loading，防止第一次进入界面时出现短暂空白
	NextLoading.start();
};
</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 20px;
	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}
	.login-content-password {
		display: inline-block;
		width: 20px;
		cursor: pointer;
		&:hover {
			color: #909399;
		}
	}
	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-size: 16px;
		font-weight: 600;
		margin-top: 15px;
	}
}
</style>
